<template>
  <div class="taobao-layout">
    <!-- 头部区域（保持原有样式和方法） -->
    <header class="main-header">
      <!-- 主导航区 -->
      <div class="header-nav">
        <div class="container">
          <div class="logo">
            <el-icon class="logo-icon">
              <ShoppingBag />
            </el-icon>
            <span class="logo-text">淘宝宝</span>
          </div>

          <div class="search-container">
            <el-input
                v-model="searchQuery"
                placeholder="搜索商品、品牌或店铺"
                class="search-input"
                @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button
                    type="primary"
                    class="search-btn"
                    @click="handleSearch"
                >
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
              </template>
            </el-input>
          </div>

          <div class="user-actions">
            <div class="action-item" @click="goToPage('home')">首页</div>
            <div class="action-item" @click="goToPage('orders')">已买到的宝贝</div>
            <div class="action-item" @click="goToPage('cart')">
              <el-icon><ShoppingCart /></el-icon>
              <span>购物车</span>
              <span class="cart-count" v-if="cartCount > 0">{{ cartCount }}</span>
            </div>
            <div class="action-item" @click="goToPage('user')">
              <el-icon><Menu /></el-icon>
              <span>我的淘宝</span>
            </div>
            <div class="action-item" @click="router.push('/shops')" >
              <el-icon><HomeFilled /></el-icon>
              <span>我的店铺</span>
            </div>
            <div class="action-item" @click="router.push('/yycsh')" v-if="!isLoggedIn">
              <el-icon><User /></el-icon>
              <span>登录</span>
            </div>
            <div class="action-item" v-if="isLoggedIn">
              <el-dropdown @command="handleUserCommand">
                <div class="user-dropdown">
                  <el-icon><User /></el-icon>
                  <span>{{ username }}</span>
                </div>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="account" @click="router.push('/account')">账号管理</el-dropdown-item>
                    <el-dropdown-item command="logout"  @click="getoutlogin">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>

      <!-- 分类导航 -->
      <div class="category-nav">
        <div class="container">
          <div class="category-item" @click="goToCategory(1)">天猫</div>
          <div class="category-item" @click="goToCategory(2)">超市</div>
          <div class="category-item" @click="goToCategory(3)">生鲜</div>
          <div class="category-item" @click="goToCategory(4)">全球购</div>
          <div class="category-item" @click="goToCategory(5)">闪购</div>
          <div class="category-item" @click="goToCategory(6)">拍卖</div>
          <div class="category-item" @click="goToCategory(7)">便宜好货</div>
          <div class="category-item" @click="goToCategory(8)">天猫国际</div>
        </div>
      </div>
    </header>

    <!-- 主内容区域 -->
    <main class="main-content container">
      <!-- 第一部分：分类、轮播图和服务卡片（等高） -->
      <div class="first-section">
        <div class="section-wrapper">
          <!-- 左侧分类栏 -->
          <aside class="categories-panel">
            <div class="sidebar-title">全部分类</div>
            <ul class="category-list">
              <li class="category-item">
                <div class="category-icon">
                  <el-icon :icon="Briefcase"></el-icon>
                </div>
                <div class="category-text">
                  <span>电脑</span>
                  <span class="divider">/</span>
                  <span>配件</span>
                  <span class="divider">/</span>
                  <span>办公</span>
                </div>
              </li>
              <li class="category-item">
                <div class="category-icon">
                  <el-icon :icon="Briefcase"></el-icon>
                </div>
                <div class="category-text">
                  <span>工业品</span>
                  <span class="divider">/</span>
                  <span>商业</span>
                  <span class="divider">/</span>
                  <span>农业</span>
                </div>
              </li>
              <li class="category-item">
                <div class="category-icon">
                  <el-icon :icon="Phone"></el-icon>
                </div>
                <div class="category-text">
                  <span>家电</span>
                  <span class="divider">/</span>
                  <span>手机</span>
                  <span class="divider">/</span>
                  <span>数码</span>
                </div>
              </li>
              <li class="category-item">
                <div class="category-icon">
                  <el-icon :icon="Phone"></el-icon>
                </div>
                <div class="category-text">
                  <span>家具</span>
                  <span class="divider">/</span>
                  <span>家装</span>
                  <span class="divider">/</span>
                  <span>家居</span>
                </div>
              </li>
              <li class="category-item">
                <div class="category-icon">
                  <el-icon :icon="Phone"></el-icon>
                </div>
                <div class="category-text">
                  <span>女装</span>
                  <span class="divider">/</span>
                  <span>男装</span>
                  <span>配饰</span>
                </div>
              </li>
              <li class="category-item">
                <div class="category-icon">
                  <el-icon :icon="Phone"></el-icon>
                </div>
                <div class="category-text">
                  <span>女鞋</span>
                  <span class="divider">/</span>
                  <span>男鞋</span>
                  <span>运动</span>
                </div>
              </li>
              <li class="category-item">
                <div class="category-icon">
                  <el-icon :icon="Phone"></el-icon>
                </div>
                <div class="category-text">
                  <span>汽车</span>
                  <span class="divider">/</span>
                  <span>珠宝</span>
                  <span>箱包</span>
                </div>
              </li>
              <li class="category-item">
                <div class="category-icon">
                  <el-icon :icon="ForkSpoon"></el-icon>
                </div>
                <div class="category-text">
                  <span>食品</span>
                  <span class="divider">/</span>
                  <span>生鲜</span>
                  <span>酒类</span>
                </div>
              </li>
              <li class="category-item">
                <div class="category-icon">
                  <el-icon :icon="Phone"></el-icon>
                </div>
                <div class="category-text">
                  <span>母婴</span>
                  <span class="divider">/</span>
                  <span>童装</span>
                  <span>玩具</span>
                </div>
              </li>
              <li class="category-item">
                <div class="category-icon">
                  <el-icon :icon="Phone"></el-icon>
                </div>
                <div class="category-text">
                  <span>美妆</span>
                  <span class="divider">/</span>
                  <span>个护</span>
                  <span>图书</span>
                </div>
              </li>
            </ul>
          </aside>

          <!-- 中间轮播图 -->
          <section class="carousel-panel">
            <el-carousel height="100%" class="main-carousel">
              <el-carousel-item v-for="(slide, index) in 5" :key="index">
                <img
                    :src="`https://picsum.photos/800/500?random=${index + 10}`"
                    alt="轮播图"
                    class="carousel-img"
                >
              </el-carousel-item>
            </el-carousel>
          </section>

          <!-- 右侧服务卡片 -->
          <aside class="services-panel">
            <div class="service-card equal-height">
              <div class="service-item" @click="router.push('/kefu')">
                <el-icon :icon="Help" class="service-icon"></el-icon>
                <div class="service-info">
                  <div class="service-title">客服中心</div>
                  <div class="service-desc">专业团队 随时为您服务</div>
                </div>
              </div>
            </div>

            <div class="service-card equal-height">
              <div class="service-item">
                <el-icon :icon="Truck" class="service-icon"></el-icon>
                <div class="service-info">
                  <div class="service-title">物流保障</div>
                  <div class="service-desc">快速配送 全程跟踪</div>
                </div>
              </div>
            </div>

            <div class="service-card equal-height">
              <div class="service-item">
                <el-icon :icon="Shield" class="service-icon"></el-icon>
                <div class="service-info">
                  <div class="service-title">消费者保障</div>
                  <div class="service-desc">正品保障 七天无理由</div>
                </div>
              </div>
            </div>

            <div class="service-card equal-height">
              <div class="service-item">
                <el-icon :icon="Clock" class="service-icon"></el-icon>
                <div class="service-info">
                  <div class="service-title">售后时间</div>
                  <div class="service-desc">9:00-22:00 全天候服务</div>
                </div>
              </div>
            </div>
          </aside>
        </div>
      </div>

      <!-- 第二部分：商品卡片展示区（无限滚动） -->
      <div class="second-section">
        <div class="section-title">精选商品</div>
        <div
            class="products-container"
            @scroll="handleScroll"
            ref="productsScrollContainer"
        >
          <div class="products-grid">
            <div class="product-card" v-for="(product, index) in products" :key="index">
              <div class="product-img-container">
                <img :src="product.imgUrl" alt="商品图片" class="product-img">
                <div class="product-badge" v-if="product.badge">{{ product.badge }}</div>
              </div>
              <div class="product-name">{{ product.name }}</div>
              <div class="product-price">{{ product.price }}</div>
              <div class="product-sales">
                <el-icon class="sales-icon"><Goods /></el-icon>
                {{ product.sales }}人已买
              </div>
              <el-button class="add-to-cart" size="small" @click="addToCart">
                <el-icon><ShoppingCart /></el-icon>
                加入购物车
              </el-button>
            </div>
          </div>

          <!-- 加载指示器 -->
          <div class="loading-indicator" v-if="isLoading">
            <el-loading-spinner></el-loading-spinner>
            <span>加载中...</span>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="main-footer">
      <div class="container">
        <div class="footer-links">
          <div class="link-group">
            <div class="link-title">淘宝特色</div>
            <div class="link-item">闲鱼</div>
            <div class="link-item">天猫</div>
            <div class="link-item">聚划算</div>
            <div class="link-item">淘宝直播</div>
          </div>
          <div class="link-group">
            <div class="link-title">帮助中心</div>
            <div class="link-item">退款售后</div>
            <div class="link-item">投诉举报</div>
            <div class="link-item">联系客服</div>
            <div class="link-item">常见问题</div>
          </div>
          <div class="link-group">
            <div class="link-title">关于我们</div>
            <div class="link-item">公司简介</div>
            <div class="link-item">招贤纳士</div>
            <div class="link-item">联系我们</div>
            <div class="link-item">网站地图</div>
          </div>
        </div>
        <div class="copyright">© 2023 淘宝网 版权所有</div>
      </div>
    </footer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
// 假设AuthService存在于项目中
import { AuthService } from '../../service/auth';
import {
  ShoppingBag, Search, ShoppingCart, User, Menu, HomeFilled,
  Briefcase, Phone, ForkSpoon,
  Goods, Help, Clock
} from '@element-plus/icons-vue';
import { ElButton, ElInput, ElCarousel, ElCarouselItem, ElIcon, ElDropdown, ElDropdownMenu, ElDropdownItem, ElLoading } from 'element-plus';

// 认证相关
const authService = new AuthService();
const router = useRouter();
const isLoggedIn = ref(false);
isLoggedIn.value = authService.getUser() != null;
let username = ref('');
if (isLoggedIn.value && authService.getUser()) {
  username = ref(authService.getUser().username);
}

// 搜索相关
const searchQuery = ref('');
const handleSearch = () => {
  if (searchQuery.value.trim()) {
    console.log('搜索:', searchQuery.value);
    // 实际项目中这里会进行路由跳转
    // router.push(`/search?query=${encodeURIComponent(searchQuery.value)}`);
  }
};

// 购物车相关
const cartCount = ref(3);
const addToCart = () => {
  console.log('加入购物车');
  cartCount.value++;
  // 实际项目中这里会调用API添加商品到购物车
};

// 页面跳转方法
const goToPage = (page: string) => {
  console.log('前往页面:', page);
  // 实际项目中这里会进行路由跳转
  // router.push(`/${page}`);
};

// 分类跳转
const goToCategory = (id: number) => {
  console.log('前往分类:', id);
  // 实际项目中这里会进行路由跳转
  // router.push(`/category/${id}`);
};

// 退出登录
const getoutlogin = () => {
  authService.clearAuth();
  isLoggedIn.value = false;
  username.value = '';
  // 实际项目中可以添加路由跳转
  // router.push('/');
};

// 用户命令处理
const handleUserCommand = (command: string) => {
  console.log('用户命令:', command);
  if (command === 'logout') {
    getoutlogin();
  }
};

// 商品数据和无限滚动相关
const products = ref([]);
const isLoading = ref(false);
const productsScrollContainer = ref<HTMLElement | null>(null);
let currentPage = 1;
const pageSize = 10; // 每次加载的商品数量

// 生成模拟商品数据
const generateProducts = (page: number) => {
  const newProducts = [];
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;

  for (let i = startIndex; i < endIndex; i++) {
    const randomPrice = (Math.random() * 900 + 100).toFixed(2);
    const randomSales = Math.floor(Math.random() * 5000);
    const badges = ['限时7折', '立减30', '第二件半价', '买2送1', ''];
    const randomBadge = badges[Math.floor(Math.random() * badges.length)];

    newProducts.push({
      id: i,
      name: `精选商品 ${i + 1} 优质好货推荐`,
      price: `¥${randomPrice}`,
      sales: randomSales,
      badge: randomBadge,
      imgUrl: `https://picsum.photos/300/300?random=${i + 50}`
    });
  }

  return newProducts;
};

// 加载更多商品
const loadMoreProducts = () => {
  if (isLoading.value) return;

  isLoading.value = true;
  // 模拟网络请求延迟
  setTimeout(() => {
    currentPage++;
    const newProducts = generateProducts(currentPage);
    products.value = [...products.value, ...newProducts];
    isLoading.value = false;
  }, 1000);
};

// 处理滚动事件，实现无限滚动
const handleScroll = () => {
  if (!productsScrollContainer.value) return;

  const { scrollTop, clientHeight, scrollHeight } = productsScrollContainer.value;

  // 当滚动到距离底部200px时加载更多
  if (scrollHeight - scrollTop - clientHeight < 200 && !isLoading.value) {
    loadMoreProducts();
  }
};

// 初始化页面
onMounted(() => {
  // 初始加载第一页商品
  products.value = generateProducts(currentPage);

  // 确保DOM渲染完成后设置滚动容器高度
  nextTick(() => {
    if (productsScrollContainer.value) {
      productsScrollContainer.value.style.maxHeight = `${window.innerHeight * 0.6}px`;
    }
  });
});
</script>

<style scoped>
/* 基础样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.taobao-layout {
  font-family: "Microsoft YaHei", sans-serif;
  color: #333;
  background-color: #f5f5f5;
}

.container {
  width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

/* 头部样式（保持不变） */
.main-header {
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-nav {
  padding: 15px 0;
  background-color: #fff;
}

.header-nav .container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo-icon {
  font-size: 32px;
  color: #ff4400;
}

.logo-text {
  font-size: 24px;
  font-weight: bold;
  color: #ff4400;
}

.search-container {
  flex: 1;
  max-width: 600px;
}

.search-input {
  --el-input-height: 40px;
  --el-input-bg-color: #f5f5f5;
  border-radius: 20px 0 0 20px;
}

.search-btn {
  --el-button-height: 40px;
  border-radius: 0 20px 20px 0;
  background-color: #ff4400;
  border-color: #ff4400;
  padding: 0 20px;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  color: #666;
  transition: color 0.2s;
}

.action-item:hover {
  color: #ff4400;
}

.cart-count {
  position: relative;
  top: -8px;
  right: 8px;
  background-color: #ff4400;
  color: #fff;
  font-size: 12px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.category-nav {
  background-color: #ff4400;
  padding: 8px 0;
}

.category-nav .container {
  display: flex;
  gap: 20px;
  overflow: hidden;
}

.category-item {
  color: #fff;
  font-weight: 500;
  cursor: pointer;
  white-space: nowrap;
  transition: opacity 0.2s;
}

.category-item:hover {
  opacity: 0.8;
}

/* 主内容区域 */
.main-content {
  padding: 15px 0;
}

/* 第一部分样式 */
.first-section {
  margin-bottom: 20px;
}

.section-wrapper {
  display: flex;
  gap: 15px;
  height: 500px; /* 固定高度，确保三个模块等高 */
}

/* 分类面板 */
.categories-panel {
  width: 250px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  flex-shrink: 0;
}

.sidebar-title {
  padding: 15px;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #f5f5f5;
}

.category-list {
  list-style: none;
  height: calc(100% - 50px); /* 减去标题高度 */
  overflow-y: auto;
}

.category-list .category-item {
  display: flex;
  align-items: center;
  padding: 15px;
  color: #333;
  cursor: pointer;
  transition: background-color 0.2s;
}

.category-list .category-item:hover {
  background-color: #f5f7fa;
}

.category-icon {
  margin-right: 10px;
  color: #ff4400;
}

.category-text {
  font-size: 14px;
}

.divider {
  margin: 0 5px;
  color: #ddd;
}

/* 轮播图面板 */
.carousel-panel {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.main-carousel {
  height: 100% !important;
}

.carousel-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 服务卡片面板 */
.services-panel {
  width: 250px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  flex-shrink: 0;
}

.service-card {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
}

.service-item {
  display: flex;
  align-items: center;
  width: 100%;
  cursor: pointer;
}

.service-icon {
  font-size: 32px;
  color: #ff4400;
  margin-right: 15px;
}

.service-info {
  flex: 1;
}

.service-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.service-desc {
  font-size: 12px;
  color: #666;
}

.equal-height {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 第二部分：商品展示区 */
.second-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f5f5f5;
}

.products-container {
  overflow-y: auto;
  padding-right: 10px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 15px;
}

.product-card {
  border: 1px solid #f5f5f5;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.2s, box-shadow 0.2s;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.product-img-container {
  position: relative;
}

.product-img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: #ff4400;
  color: #fff;
  font-size: 12px;
  padding: 3px 8px;
  border-radius: 4px;
}

.product-name {
  padding: 10px;
  font-size: 14px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  padding: 0 10px;
  color: #ff4400;
  font-weight: bold;
}

.product-sales {
  padding: 10px;
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
  gap: 5px;
}

.sales-icon {
  font-size: 14px;
}

.add-to-cart {
  width: calc(100% - 20px);
  margin: 0 10px 10px;
  background-color: #fff;
  color: #ff4400;
  border-color: #ff4400;
}

.add-to-cart:hover {
  background-color: #ff4400;
  color: #fff;
}

/* 加载指示器 */
.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  gap: 10px;
}

/* 页脚样式（保持不变） */
.main-footer {
  background-color: #fff;
  padding: 30px 0;
  border-top: 1px solid #f5f5f5;
}

.footer-links {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.link-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.link-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.link-item {
  color: #666;
  cursor: pointer;
  font-size: 14px;
}

.link-item:hover {
  color: #ff4400;
  text-decoration: underline;
}

.copyright {
  text-align: center;
  color: #999;
  font-size: 14px;
  padding-top: 20px;
  border-top: 1px solid #f5f5f5;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .container {
    width: 960px;
  }

  .products-grid {
    grid-template-columns: repeat(4, 1fr);
  }

  .section-wrapper {
    height: 450px;
  }
}

@media (max-width: 992px) {
  .container {
    width: 720px;
  }

  .services-panel {
    display: none;
  }

  .products-grid {
    grid-template-columns: repeat(3, 1fr);
  }

  .section-wrapper {
    height: 400px;
  }
}

@media (max-width: 768px) {
  .container {
    width: 100%;
  }

  .categories-panel {
    display: none;
  }

  .products-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .section-wrapper {
    height: 300px;
  }

  .header-nav .container {
    flex-wrap: wrap;
  }

  .search-container {
    order: 3;
    width: 100%;
    margin-top: 10px;
  }

  .footer-links {
    flex-wrap: wrap;
  }

  .link-group {
    flex: 1 1 calc(50% - 10px);
    margin-bottom: 20px;
  }
}

@media (max-width: 576px) {
  .products-grid {
    grid-template-columns: 1fr;
  }

  .section-wrapper {
    height: 250px;
  }
}
</style>
